package com.extsci.webmail.aspect;

import com.extsci.webmail.common.entity.http.ObjectRestResponse;
import com.extsci.webmail.common.entity.http.ResponseStatus;
import com.extsci.webmail.common.entity.mail.Attachment;
import com.extsci.webmail.common.entity.mail.Mail;
import com.extsci.webmail.common.type.PositionType;
import com.extsci.webmail.common.util.MyFileUtils;
import com.extsci.webmail.exception.SensitiveException;
import com.extsci.webmail.web.service.SensitiveService;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;


/**
 * 敏感词过滤
 * @author ccoke
 */
@Aspect
@Component
@Log4j
public class SensitiveAspect {

    private final SensitiveService sensitiveService;

    @Autowired
    public SensitiveAspect(SensitiveService sensitiveService) {
        this.sensitiveService = sensitiveService;
    }

    /**
     * 发送邮件前进行过滤
     */
    @Around("execution(* com.extsci.webmail.web.controller.MailController.postMail(..))")
    public ObjectRestResponse<String> doAround(ProceedingJoinPoint pjp) throws Throwable {
        Mail mail = (Mail) pjp.getArgs()[0];
        try {
            // 跳过草稿箱
            if (Optional.ofNullable(mail.getIsDraft()).orElse(false)) {
                return (ObjectRestResponse<String>) pjp.proceed();
            }

            if (StringUtils.isNotBlank(mail.getSubject())){
                String subject = sensitiveService.inspect(mail.getSubject(), PositionType.SUBJECT);
                mail.setSubject(subject);
            }

            if (StringUtils.isNotBlank(mail.getBody())){
                String body = sensitiveService.inspect(mail.getBody(), PositionType.BODY);
                mail.setBody(body);
            }
            List<Attachment> attachments = mail.getAttachments();
            if (attachments != null && attachments.size() > 0){
                for (int i = 0; i < attachments.size(); i++) {
                    String fileName = MyFileUtils.getFileNameByURI(attachments.get(i).getUri());
                    String attachmentName = sensitiveService.inspect(fileName, PositionType.ATTACHMENT);
                    attachments.get(i).setName(attachmentName);
                }
            }
            return (ObjectRestResponse<String>) pjp.proceed();
        } catch (SensitiveException e) {
            e.printStackTrace();
            log.warn("敏感词过滤:" + e.getMessage());
            return new ObjectRestResponse(ResponseStatus.CANNOT_SEND_EMAIL_CASE_BY_SENSITIVE);
        }
    }

}
